﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data.Linq;
using System.Net;
using System.IO;

namespace Playerstats
{
    public class Parser
    {
        TravianLib.HTTPFetch htp;
       
        public enum Race
        {
            Unknown = 0,
            Teutons = 1,
            Romans = 2,
            Gallic = 3,
            Nature = 4,
            Natar = 5
        }
        public enum Server
        {
            s2fi = 0
        }
        public Parser()
        {
             htp = new TravianLib.HTTPFetch("momimimi", "E0NzgLF7", "s2.travian.fi");
             htp.NewHttpRequest += new TravianLib.HTTPFetch.HttpRequestEventHandler(htp_NewHttpRequest);
        }

        void htp_NewHttpRequest(System.Net.WebRequest wr)
        {            
           
        }
        //private Village createVillage(int c, int d, string name, int x, int y, Player pl)
        //{
        //    Village output = new Village();

        //    output = new Village();
        //    output.C = c;
        //    output.D = d;

        //    output.Player = pl;
        //    output.Name = name;
        //    output.X = x;
        //    output.Y = y;

        //    return output;
        //}
        public void DeleteDead()
        {
            DataLoadOptions options = new DataLoadOptions();
            options.LoadWith<Player>(c => c.Villages);
            options.LoadWith<Village>(p => p.Histories);
            Stats db = new Stats();
            db.LoadOptions = options;

            foreach (Player pl in db.Players)
            {
                foreach (Village vil in pl.Villages)
                {
                    History his = (from hs in vil.Histories
                                   orderby hs.Date descending
                                   select hs).First();
                    if (his.Date < DateTime.Now.AddDays(-2))
                    {
                        db.Histories.DeleteAllOnSubmit(vil.Histories);
                        db.Villages.DeleteOnSubmit(vil);                        
                    }
                }
            }
            db.Players.DeleteAllOnSubmit(from pl in db.Players
                     where pl.Villages.Count == 0
                     select pl);
            db.SubmitChanges();
        }
        public void ParseSQLFile(string url, Server serv)
        {
            Regex vilRegex = new Regex("VALUES .([0-9]+),([-0-9]+),([-0-9]+),([0-9]+),([0-9]+),'(.*?)',([0-9]+),'(.*?)',([0-9]+),'(.*?)',([0-9]+)");
            WebClient Client = new WebClient();          
            Stream strm = Client.OpenRead(url);
            Stats db = new Stats();
            
            string contents = "";
            using (StreamReader reader = new StreamReader(strm))
            {
                contents = reader.ReadToEnd();
            }
            MatchCollection vilCollection = vilRegex.Matches(contents);

            foreach (Match item in vilCollection)
            {
                int id = int.Parse(item.Groups[1].Value);
                int x = int.Parse(item.Groups[2].Value);
                int y = int.Parse(item.Groups[3].Value);
                int tid = int.Parse(item.Groups[4].Value);
                int vid = int.Parse(item.Groups[5].Value);
                string village = item.Groups[6].Value;
                int uid = int.Parse(item.Groups[7].Value);
                string player = item.Groups[8].Value;
                int aid = int.Parse(item.Groups[9].Value);
                string alliance = item.Groups[10].Value;
                int population = int.Parse(item.Groups[11].Value);

                Player pl = (from p in db.Players
                             where p.PlayerID == uid
                             select p).SingleOrDefault();
                if (pl != null)
                {
                    pl.Alliance = aid;
                }
                else
                {
                    pl = new Player();
                    pl.Alliance = aid;
                    pl.Name = player;
                    pl.Tribe = (Race)tid;
                    pl.PlayerID = uid;
                    pl.Server = serv;
                    db.Players.InsertOnSubmit(pl);
                    db.SubmitChanges();
                }
                Village vil = (from v in pl.Villages
                               where v.VillageID == id
                               select v).SingleOrDefault();
                if (vil != null)
                {
                    vil.Name = village;
                    vil.Player = pl;
                }
                else
                {
                    vil = new Village();
                    vil.Name = village;
                    vil.VillageID = id;
                    vil.X = x;
                    vil.Y = y;
                    vil.Player = pl;
                    pl.Villages.Add(vil);
                }
                History hs = new History();
                hs.Date = DateTime.Now;
                hs.Size = population;

                vil.Histories.Add(hs);

            }
            db.SubmitChanges();
        }
        //public void ParsePlayerList()
        //{
        //    Stats db = new Stats();
        //    System.Data.Linq.DataLoadOptions options = new System.Data.Linq.DataLoadOptions();

        //    db.LoadOptions = options;
        //    if (!db.DatabaseExists())
        //    {
        //        try
        //        {
        //            db.CreateDatabase();
        //        }
        //        catch (Exception ex)
        //        {
        //            System.Windows.Forms.MessageBox.Show(ex.ToString());
        //        }
        //    }
        //    Regex villageRegex = new Regex("<td class=\"vil \" >.*?d=([0-9]+).*?;c=([a-f0-9]+)\">(.*?)<");
        //    Regex playerRegex = new Regex("<td class=\"pla.*?(uid=)([0-9]+)\">(.*?)<");
        //    Regex coordinatesRegex = new Regex("([-0-9]+)<.*?coy\">([-0-9]+)");
        //    Regex rankRegex = new Regex("statistiken.php.id=2&.*?rank=([0-9]+)");
        //    Regex sizeRegex = new Regex("<td class=\"hab \" >([0-9]+)");
        //    string output = htp.createHTTPrequest("http://s2.travian.fi/statistiken.php?id=2&rank=999999#h2");
        //    int rank = 999999;

        //    var players = (from c in db.Players                              
        //                       select c);
             
        //    while (rank > int.Parse(rankRegex.Match(output).Groups[1].Value))
        //    {
        //        rank = int.Parse(rankRegex.Match(output).Groups[1].Value);
        //        MatchCollection matchesPlayers = playerRegex.Matches(output);
        //        MatchCollection matchesVillages = villageRegex.Matches(output);
        //        MatchCollection matchesCoordinates = coordinatesRegex.Matches(output);
        //        MatchCollection matchesSizes = sizeRegex.Matches(output);

        //        if (matchesCoordinates.Count == matchesVillages.Count && matchesVillages.Count == matchesPlayers.Count)
        //        {
        //            for (int i = 0; i < matchesVillages.Count; i++)
        //            {

        //                Player pl = (from c in players
        //                             where c.PlayerID == int.Parse(matchesPlayers[i].Groups[2].Value)
        //                             select c).SingleOrDefault();
        //                Village vil = new Village();
        //                if (pl == null)
        //                {
        //                    pl = new Player();
        //                    pl.PlayerID = int.Parse(matchesPlayers[i].Groups[2].Value);
        //                    pl.Name = matchesPlayers[i].Groups[3].Value;
        //                    string outputTmp = htp.createHTTPrequest("http://s2.travian.fi/spieler.php?uid=" + pl.PlayerID);
        //                    pl.Tribe = pl.getTribe(outputTmp);
        //                    pl.Alliance = pl.getAllianceNumber(outputTmp);
        //                    pl.Server = Server.s2fi;

        //                    vil = createVillage(int.Parse(matchesVillages[i].Groups[1].Value), int.Parse(matchesVillages[i].Groups[2].Value, System.Globalization.NumberStyles.HexNumber), matchesVillages[i].Groups[3].Value, int.Parse(matchesCoordinates[i].Groups[1].Value), int.Parse(matchesCoordinates[i].Groups[2].Value), pl);
                            
        //                    db.Players.InsertOnSubmit(pl);
        //                }
        //                else
        //                {
        //                    vil = (from c in pl.Villages
        //                                   where c.C == int.Parse(matchesVillages[i].Groups[1].Value) &&
        //                                   c.D == int.Parse(matchesVillages[i].Groups[2].Value, System.Globalization.NumberStyles.HexNumber)
        //                                   select c).SingleOrDefault();
        //                    if (vil == null)
        //                    {
        //                        vil = createVillage(int.Parse(matchesVillages[i].Groups[1].Value), int.Parse(matchesVillages[i].Groups[2].Value, System.Globalization.NumberStyles.HexNumber), matchesVillages[i].Groups[3].Value, int.Parse(matchesCoordinates[i].Groups[1].Value), int.Parse(matchesCoordinates[i].Groups[2].Value), pl);
        //                    }
        //                }
        //                vil.Name = matchesVillages[i].Groups[3].Value;
        //                History hs = new History();
        //                hs.Date = DateTime.Now;
        //                hs.Size = int.Parse(matchesSizes[i].Groups[1].Value);

        //                vil.Histories.Add(hs);                        
        //            }                    
        //        }
        //        output = htp.createHTTPrequest("http://s2.travian.fi/statistiken.php?id=2&rank=" + rank + "#h2");
        //        db.SubmitChanges();                
        //        OnePageParsed(this,new EventArgs());
        //    }
        //    db.Dispose();
        //}
    }
}
